<template>
    <GetanDrawer @register="register" @on-ok="handleSubmit">
        <n-tree block-line checkable default-expand-all :data="permissionTree" :checked-keys="permissionIds" @update:checked-keys="handleSelect" />
    </GetanDrawer>
</template>

<script setup lang="ts">
import { useGetanDrawer, GetanDrawer } from "@/components/Drawer"
import { api } from "../../api"
import { isEmpty } from "@/utils"
import { TreeOption } from "naive-ui"

const { register, methods } = useGetanDrawer({ width: 600 })

const permissionTree = ref<TreeOption[]>([])
const permissionIds = ref<string[]>([])
const roleId = ref<string>("")

const handleSelect = (keys: string[]) => {
    permissionIds.value = keys
}

const loadPermissionTree = async () => {
    const { res, isOk } = await api.permissionTree()
    if (isOk()) {
        permissionTree.value = parseTreeOption(res.value ?? [])
    }
}

function parseTreeOption(permissions: Recordable[]) {
    return permissions.map(permission => {
        const p: TreeOption = {
            key: permission.id,
            label: permission.name
        }
        if (!isEmpty(permission.children)) {
            p.children = parseTreeOption(permission.children)
        }
        return p
    })
}

const instance = getCurrentInstance()
if (instance) {
    loadPermissionTree()
}

const allocPermission = async (rowData: Recordable) => {
    methods.open(`权限 -【${rowData.name}】`)
    if (rowData.id !== roleId.value) {
        permissionIds.value = []
        roleId.value = rowData.id
        const { res, isOk } = await api.permissionIds({ id: roleId.value })
        if (isOk()) {
            permissionIds.value = res.value
        }
    }
}

defineExpose({ allocPermission })

const handleSubmit = async () => {
    await api.allocPermission({ roleId: roleId.value, permissionIds: permissionIds.value })
}
</script>
